package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    //创建一个计数器，每次请求服务端的时候轮询切换ip+port，从而实现负载轮询调用

    //被static修饰,表明被所有对象共享
    static RpcClient rpcClient;

    static final List<RpcClient> rpcClientList = new ArrayList<>();

    //随着类的加载而执行，而且只执行一次,执行完成便销毁
    static {
        rpcClientList.add(new RpcClient("127.0.0.1",8899));
        rpcClientList.add(new RpcClient("127.0.0.1",8898));
    }

    static int count = 0;

    public static RpcClient getRpcClient(){
        //复位处理,当count>=0时,复位成0
        if(count >= rpcClientList.size()){
            count = 0;
        }
        RpcClient rpcClient = rpcClientList.get(count);
        count++;
        return  rpcClient;
      /*  while(count < rpcClientList.size()){
            RpcClient rpcClient = rpcClientList.get(count);
            count++;
        }
        count = 0;
        return rpcClient;*/
    }


    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = getRpcClient();
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            System.out.println("当前ip为:"+rpcClient.getIp());
                            System.out.println("当前port为:"+rpcClient.getPort());
                            System.out.println("当前msg为:"+result.toString());
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        }
                        /*finally {
                            rpcClient.close();
                        }*/

                    }
                });
    }
}
